package com.xiaobai.netease_news.fragments;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.adapters.ReadListAdapter;
import com.xiaobai.netease_news.constants.Constant;
import com.xiaobai.netease_news.model.ReadRecommendData;
import com.xiaobai.netease_news.utils.CommonHttpUtil;
import com.xiaobai.netease_news.views.CircleProgressBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ReadListFragment extends Fragment
        implements SwipeRefreshLayout.OnRefreshListener,
        AbsListView.OnScrollListener, View.OnClickListener, AdapterView.OnItemClickListener {

    private List<ReadRecommendData> readRecommendDataList;
    private ReadListAdapter adapter;
    private String readUrl;
    private SwipeRefreshLayout readSwipeRefresh;
    private boolean isBottom;
    private LinearLayout readLoading;
    private boolean isProgressBarShow;
    private CircleProgressBar readLoadingProgressBar;

    // 暂定
    private boolean isLogin;

    public ReadListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args != null) {
            String argsString = args.getString(Constant.ARG_CONTENT_LIST_TYPE);

            if (argsString != null) {
                if (argsString.equals(Constant.READ_RECOMMEND)) {
                    readUrl = "http://c.3g.163.com/recommend/getSubDocPic?passport=&devId=000000000000000&size=20&from=yuedu";
                } else if (argsString.equals(Constant.READ_MY)) {
                    readUrl = "";
                }

            }
        }

        readRecommendDataList = new ArrayList<>();
        adapter = new ReadListAdapter(getActivity(), readRecommendDataList);

        new readListTask().execute(readUrl, "1");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_read_list, container, false);

        readLoading = (LinearLayout) view.findViewById(R.id.read_list_loading_layout);

        readSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.read_swipe_refresh);
        readSwipeRefresh.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        readSwipeRefresh.setOnRefreshListener(this);

        ListView readListView = (ListView) readSwipeRefresh.findViewById(R.id.item_list);
        LinearLayout loginHeader = (LinearLayout) inflater.inflate(R.layout.login_header_layout, null);
        if (!isLogin)
            readListView.addHeaderView(loginHeader);
        Button loginNow = (Button) loginHeader.findViewById(R.id.login_now);
        loginNow.setOnClickListener(this);
        readListView.setAdapter(adapter);
        readListView.setOnScrollListener(this);
        readListView.setOnItemClickListener(this);

        readLoadingProgressBar = (CircleProgressBar) view.findViewById(R.id.read_loading);
        if (!isProgressBarShow)
            readLoadingProgressBar.setVisibility(View.VISIBLE);
        else
            readLoadingProgressBar.setVisibility(View.GONE);

        isProgressBarShow = true;

        return view;
    }

    @Override
    public void onRefresh() {
        new readListTask().execute(readUrl, "1");
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            readLoading.setVisibility(View.VISIBLE);
            new readListTask().execute(readUrl, "2");
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        isBottom = (firstVisibleItem + visibleItemCount) == totalItemCount;
    }

    @Override
    public void onClick(View v) {
        // TODO 转跳到登录页面
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ReadRecommendData readRecommendData = readRecommendDataList.get(position);

    }

    private class readListTask extends AsyncTask<String, Void, JSONObject> {

        private String type;

        @Override
        protected JSONObject doInBackground(String... params) {
            type = params[1];
            String url = params[0];

            byte[] bytes = CommonHttpUtil.doGet(url);
            if (bytes != null) {
                try {
                    String jsonString = new String(bytes, "utf-8");
                    return new JSONObject(jsonString);
                } catch (UnsupportedEncodingException | JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (readLoadingProgressBar.getVisibility() == View.VISIBLE)
                readLoadingProgressBar.setVisibility(View.GONE);

            readSwipeRefresh.setRefreshing(false);
            readLoading.setVisibility(View.GONE);

            if (jsonObject != null) {
                List<ReadRecommendData> readRecommendDatas = new ArrayList<>();
                try {
                    JSONArray array = jsonObject.getJSONArray("推荐");
                    int length = array.length();
                    for (int i = 0; i < length; i++) {
                        JSONObject object = array.getJSONObject(i);
                        ReadRecommendData readRecommendData = new ReadRecommendData();
                        readRecommendData.parseJson(object);

                        readRecommendDatas.add(readRecommendData);
                    }

                    if (type.equals("1")) {
                        readRecommendDataList.clear();
                        readRecommendDataList.addAll(0, readRecommendDatas);
                    } else if (type.equals("2")) {
                        readRecommendDataList.addAll(readRecommendDatas);
                    }

                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            super.onPostExecute(jsonObject);
        }
    }
}
